from google.appengine.ext import webapp
from google.appengine.api.urlfetch import fetch , GET , POST , DELETE
from com.blogspot.zizon.twitter.Oauth import quote , unquote
from com.blogspot.zizon.twitter.Oauth import Oauth
import logging

# proxy apis
class RestApiProxy(webapp.RequestHandler): 
    
    # overide this method to get proxied api server url
    def getApiServer(self):
        return "";
 
    # pre-set http oauth headers
    def prepareHeader(self, method, parameters):
        # need authorize 
        if "Authorization" in self.request.headers and Oauth.identity() in self.request.headers["Authorization"] and "Oauth" not in self.request.headers["Authorization"]:
            logging.info("Authorization introspection ,Authorization: %s" % self.request.headers["Authorization"])
            # pop authorization first
            header = Oauth.buildOauthHeader()
            header.update(parameters)
            header["oauth_signature"] = Oauth.signingRequest(
                                                             method,
                                                             "%s%s" % (
                                                                    self.getApiServer(),
                                                                    self.request.path.replace("/twitter/", ""),
                                                                   ),
                                                             header,
                                                            Oauth.comsumer_secret,
                                                            Oauth.oauth_token_secret)
            self.request.headers["Authorization"] = "OAuth %s" % (", ".join("%s=\"%s\"" % (quote(key), quote(value)) for key, value in header.items()))
            
    # just forward request , replacing original host
    def proxy(self , method , *args):
        logging.info("request url: %s , header: %s , query_string: %s , body: %s" % (self.request.url, self.request.headers, self.request.query_string, self.request.body))
        # do api proxy
        response = fetch(
                            "%s%s?%s" % (
                                            self.getApiServer() ,
                                            self.request.path.replace("/twitter/", ""),
                                            self.request.query_string
                                        ),
                            self.request.body,
                            method,
                            self.request.headers,
                        )
        self.response.headers = response.headers
        self.response.out.write(response.content)
        # loging job
        logging.info("header = %s , respondse = %s" % (response.headers, response.content))

    # handle http get   
    def get(self, *args):
        parameters = self.convertParameters(self.request.query_string)
        self.prepareHeader("GET", parameters)
        self.request.query_string = "&".join("%s=%s" % (quote(key) , quote(value)) for key, value in parameters.items())
        self.proxy(GET, *args)
        
    # handle http post
    def post(self, *args):
        parameters = self.convertParameters(self.request.body)
        self.prepareHeader("POST", parameters)
        self.request.body = "&".join("%s=%s" % (quote(key) , quote(value)) for key, value in parameters.items())
        self.proxy(POST, *args)
    
    # handle http delete   
    def delete(self , *arps):
        self.proxy(DELETE, *arps)
    
    # convert query strings to dictionary    
    def convertParameters(self, source):
        parameters = {}
        for pairs in source.split("&"):
            item = pairs.split("=")
            if len(item) == 2:
                parameters[item[0]] = unquote(item[1])
        return parameters